package com.woyou.ui.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import retrofit.RetrofitError;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.citaq.ideliver.R;
import com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.OnPreRefreshingAnimListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.woyou.BroadcastConstant;
import com.woyou.bean.ActivityType;
import com.woyou.bean.City;
import com.woyou.bean.CodeListResult;
import com.woyou.bean.FmInfoBean;
import com.woyou.bean.Info;
import com.woyou.bean.MyAddress;
import com.woyou.bean.ShopItem;
import com.woyou.bean.ShopType;
import com.woyou.bean.SortType;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.LatLngReq;
import com.woyou.bean.rpc.ShopListReq;
import com.woyou.bean.rpc.ShopTypeReq;
import com.woyou.service.LocationLoopService;
import com.woyou.service.LocationLoopService.LocationChangeListener;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.activity.AddrSearchActivity_;
import com.woyou.ui.activity.MyCouPonActivity_;
import com.woyou.ui.activity.ShopInfoActivity;
import com.woyou.ui.activity.ShopsSearchActivity_;
import com.woyou.ui.adapter.ShopListAdapter;
import com.woyou.ui.component.ActivityTypePop;
import com.woyou.ui.component.ActivityTypePop.ActTypeListener;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.ErrorHintView.FilterShopImp;
import com.woyou.ui.component.ErrorHintView.OperateListener;
import com.woyou.ui.component.ShopTypePop;
import com.woyou.ui.component.ShopTypePop.ShopTypeListener;
import com.woyou.ui.component.SortTypePop;
import com.woyou.ui.component.SortTypePop.SortTypeListener;
import com.woyou.ui.component.SuperUI;
import com.woyou.ui.component.fastscroll.FastScrollView;
import com.woyou.ui.component.fastscroll.IdleListDetector;
import com.woyou.ui.component.fastscroll.IdleListener;
import com.woyou.utils.LogUtil;
import com.woyou.utils.Task;
import com.woyou.utils.eventbus.EventHideUpdate;
import com.woyou.utils.eventbus.EventShowBar;

import de.greenrobot.event.EventBus;

/**
 * 商户碎片
 * 
 * @author longtao.li
 */
@EFragment(R.layout.fm_shops)
public class ShopsFragment extends SuperFragment implements OnClickListener {

	private static final String TAG = "ShopsFragment";

	@ViewById(R.id.shop_list)
	PullToRefreshListView shopList;
	@ViewById(R.id.shops_filter_type_ll)
	View filterType;
	@ViewById(R.id.shops_filter_conditions_ll)
	View filterSort;
	@ViewById(R.id.shops_filter_activities_ll)
	View filterActi;
	@ViewById(R.id.shops_filter_type_tv)
	TextView typeTv; // 全部类型
	@ViewById(R.id.shops_filter_type_iv)
	ImageView typeIv;
	@ViewById(R.id.shops_filter_conditions_tv)
	TextView conditionsTv; // 附近距离
	@ViewById(R.id.shops_filter_conditions_iv)
	ImageView conditionsIv;
	@ViewById(R.id.shops_filter_activities_tv)
	TextView activityTv; // 优惠活动
	@ViewById(R.id.shops_filter_activities_iv)
	ImageView activityIv;

	@ViewById(R.id.search_address)
	TextView locationAddr; // 定位地址
	@ViewById(R.id.shade)
	FrameLayout mBgShade; // 背景的遮罩
	@ViewById(R.id.load_shoping)
	RelativeLayout loadShoping; // 正在加载中
	@ViewById(R.id.img_rotate)
	ImageView rotateImg; // 旋转的图片
	@ViewById(R.id.hintView)
	ErrorHintView mErrorHintView;

	@ViewById(R.id.shops_filter_type_ll)
	LinearLayout typell;
	@ViewById(R.id.shops_filter_conditions_ll)
	LinearLayout conditionsll;
	@ViewById(R.id.shops_filter_activities_ll)
	LinearLayout activitiesll;

	// 店铺列表
	private List<ShopItem> shopItems = new ArrayList<ShopItem>(); // listview数据源
	private ShopListReq shopListReq = new ShopListReq();
	private ShopListAdapter shopAdapter;

	private FastScrollView fastScroller; // 快速滚动器
	private IdleListener idleListener; // 空闲监听器
	@SuppressWarnings("unused")
	private IdleListDetector mPostScrollLoader; // 空闲状态解析器

	private ShopTypePop mShopTypePop; // 商铺类型筛选POP
	private SortTypePop mSortTypePop; // 距离排序优先POP
	private ActivityTypePop mActivityTypePop; // 优惠活动筛选pop

	private MyLocationListener mLocationListener;
	private MyAddress searchAddr; // 从地址定位界面传过来的经纬度

	/** 显示店铺列表 **/
	private int VIEW_SHOPLIST = 1;
	/** 显示断网 **/
	private int VIEW_WIFIFAILUER = 2;
	/** 显示加载数据失败 **/
	private int VIEW_LOADFAILURE = 3;
	/** 显示定位失败 **/
	private int VIEW_LOCATIONFAILURE = 4;
	/** 显示加载中 **/
	private int VIEW_LOADING = 5;
	/** 显示请求超时 **/
	private int VIEW_OUTTIME = 6;
	/** 显示没有数据 **/
	private int VIEW_NOSHOPS = 7;
	/** 显示过滤店铺没有数据 **/
	private int VIEW_NOFILTERSHOPS = 8;

	// 定位 的Timer
	int point = 0;
	Timer pointTimer = null;
	TimerTask pointTimerTask = null;

	private LinearLayout footerView; // 最后一条listview
	private LocationLoopService mLocationLoopService;

	protected void setupIdleListener(AbsListView list) {
		idleListener = new IdleListener(list, 0);
		mPostScrollLoader = new IdleListDetector(idleListener);
		fastScroller = (FastScrollView) shopList.getParent();
		// fastScroller.setOnIdleListDetector(mPostScrollLoader);
		fastScroller.setScrollListener(shopList);

		shopList.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if (refreshView.isHeaderShown()) {
					pageNext = 1;
					shopListReq.setPage(1);
					refreshData(true, true);
				}
			}
		});

		shopList.setOnPreRefreshingAnimListener(new OnPreRefreshingAnimListener() {
			@Override
			public void onPreRefreshingAnim() {
				shopList.setFooterLoadingViewHeaderText("加载更多店铺");
			}
		});

		shopList.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
			@Override
			public void onLastItemVisible() {
				if (pageNext == 0) { // 没有下一页了
					shopList.onRefreshComplete();
					if (footerView == null) {
						footerView = (LinearLayout) View.inflate(mContext, R.layout.item_pull_to_refresh_footer, null);
						TextView footer = (TextView) footerView.findViewById(R.id.footer);
						footer.setText("到底了呢");
						shopList.getRefreshableView().addFooterView(footerView);
					}
				} else {
					refreshData(false, true);// 滑动到底部自动刷新
				}
			}
		});
	}

	@AfterViews
	void afterView() {
		register();
		mNetWorkCenter.setRetryNetwork(this);

		initListView();// 初始化ListView
		initFilter();// 初始化过滤器
		isLocationReady = false;
		executeAnim(locationAddr);
		showViewById(VIEW_LOADING);

		if (mLocationListener == null) {
			mLocationListener = new MyLocationListener();
			mBaiduLocationService.registerLocationListenner(mLocationListener);
		}
		mLocationLoopService = LocationLoopService.getInstance(mContext);
		mLocationLoopService.setLocationChangeListener(new LocationChangeListener() {

			@Override
			public void locationChange(final BDLocation location) {

				if (searchAddr != null) {
					mLocationLoopService.setLocationUpdateMinTime(60 * 30 * 1000);
					searchAddr = null;
					return;
				}
				SuperUI.openBottomDialog(mContext, "您的位置已变化,使用新位置吗?", "不更改", new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						SuperUI.dismiss();

					}
				}, "更新位置", new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mLocationLoopService.setLocationUpdateMinTime(60 * 1000);
						SuperUI.dismiss();
						showViewById(VIEW_LOADING);
						defParams();
						shopListReq.setLat(location.getLatitude() + "");
						shopListReq.setLng(location.getLongitude() + "");

						String addrName = location.getAddrStr();
						if (addrName != null && !"".equals(addrName)) {
							locationAddr.setText(addrName);
						}
						refreshData(true, true);
					}
				});
			}
		});
	}

	private void initListView() {
		shopAdapter = new ShopListAdapter(shopItems, mContext);
		shopList.setAdapter(shopAdapter);
		setupIdleListener(shopList.getRefreshableView());
	}

	/**
	 * 初始化过滤器
	 */
	private void initFilter() {
		typell.setOnClickListener(this);
		conditionsll.setOnClickListener(this);
		activitiesll.setOnClickListener(this);

		mShopTypePop = ShopTypePop.getInstance(mContext, filterType, mBgShade);
		mShopTypePop.setItemClickListener(new ShopTypeListener() {
			@Override
			public void itemClick(ShopType sortType) {
				// activityTv.setText("特色优惠");
				// defParams();
				showViewById(VIEW_LOADING);
				defFilter();
				shopListReq.setScope(sortType.getsTypeId());
				refreshData(true, false);
			}
		});

		mSortTypePop = SortTypePop.getInstance(mContext, filterSort, mBgShade);
		mSortTypePop.init();
		mSortTypePop.setItemClickListener(new SortTypeListener() {
			@Override
			public void itemClick(SortType sortType) {
				// defParams();
				showViewById(VIEW_LOADING);
				defFilter();
				shopListReq.setSortType(sortType.getCode());
				refreshData(true, false);
			}
		});

		mActivityTypePop = ActivityTypePop.getInstance(mContext, filterActi, mBgShade);
		mActivityTypePop.setItemClickListener(new ActTypeListener() {
			@Override
			public void itemClick(ActivityType activityType) {
				// typeTv.setText("全部类型");
				// defParams();
				showViewById(VIEW_LOADING);
				defFilter();
				String[] arrays = (String[]) activityType.getCodeList()
						.toArray(new String[activityType.getCodeList().size()]);
				shopListReq.setCodeList(arrays);
				refreshData(true, false);
			}

			@Override
			public void showAllShops(ActivityType activityType) {
				if (activityType != null) {
					String[] arrays = (String[]) activityType.getCodeList()
							.toArray(new String[activityType.getCodeList().size()]);
					shopListReq.setCodeList(arrays);
					refreshData(true, false);
				}
			}
		});
	}

	@Click(R.id.right)
	void openSearchView() { // 搜索店铺
		openActivity(ShopsSearchActivity_.class, null);
	}

	@Click({ R.id.search_address, R.id.location_icon })
	void openAddrSearchView() { // 搜索地址
		openActivity(AddrSearchActivity_.class, null);
	}

	@ItemClick(R.id.shop_list)
	public void shopListItemClick(int position) {
		ShopItem shopItem = shopItems.get(position - 1);
		Info<ShopItem> info = new Info<ShopItem>(shopItem);
		info.setOrigin(ShopsFragment_.class);
		openActivity(ShopInfoActivity.class, info);
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			if (footerView != null) {
				shopList.getRefreshableView().removeFooterView(footerView);
				footerView = null;
			}
			mLocationLoopService.startLocation();
			EventBus.getDefault().post(new EventShowBar(2));
		} else {
			// 修改activity的bug
			affertName = null;
			mLocationLoopService.stop();
			mSortTypePop.dismissPop();
			mActivityTypePop.dismissPop();
			mShopTypePop.dismissPop();
			EventBus.getDefault().post(new EventHideUpdate(2));
		}
	}

	private boolean isLocationReady = false;
	private double lat, lng;
	private LatLngReq latLngReq = new LatLngReq();
	private ShopTypeReq shopTypeReq = new ShopTypeReq();

	/**
	 * 接收事件:定位成功
	 * 
	 * @author tanglc
	 * 
	 */
	class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			mBaiduLocationService.stop();
			if (isLocationReady)
				return;

			if (!NetWorkCenter.isNetworkConnected(getActivity())) { // 断网
				cancelAnim();
				runOnUi(new Runnable() {
					@Override
					public void run() {
						locationAddr.setText("定位失败");
						showViewById(VIEW_WIFIFAILUER);
						return;
					}
				});
			}

			if (location != null) {
				defParams();
				cancelAnim();
				lat = location.getLatitude();
				lng = location.getLongitude();
				String str = lat + "";
				if (str.equals("4.9E-324")) { // 百度定位失败，搞不定看教程
					locationAddr.setText("定位失败");
					showViewById(VIEW_LOCATIONFAILURE);
					return;
				}
				shopListReq.setLat(lat + ""); // 用户纬度
				shopListReq.setLng(lng + ""); // 用户经度
				UserInfo userInfo = mUserModel.getUserInfo();
				if (userInfo == null) {
					userInfo = new UserInfo();
				}
				shopListReq.setuId(userInfo.getuId()); // 用户Id
				String cityName = location.getCity();
				City city = new City();
				city.setCity(cityName);
				mUserModel.setCity(city);

				if (!TextUtils.isEmpty(location.getAddrStr())) {
					locationAddr.setText(location.getAddrStr());
				} else {
					if (NetWorkCenter.isNetworkConnected(getActivity())) { // 有网络获取不到定位地址
						locationAddr.setText("无法获取地址名称");
					} else {
						locationAddr.setText("定位失败");
						showViewById(VIEW_LOCATIONFAILURE);
						return;
					}
				}
				lastTask = new RefreshDataTask(lastTask.getID() + 1, true, true);
				executeTask(lastTask);
				mLocationListener = null;
				isLocationReady = true;
				LogUtil.d(TAG, "lat:" + location.getLatitude() + "lng:" + location.getLongitude());

				// 加载店铺类型
				shopTypeReq.setLat(lat + "");
				shopTypeReq.setLng(lng + "");
				mShopTypePop.loadShopType(shopTypeReq, typeIv);

				// 加载优惠活动类型
				latLngReq.setLat(lat);
				latLngReq.setLng(lng);
				mActivityTypePop.loadActType(latLngReq, activityIv);

			}
		}

	}

	private int pageNext = 1;

	/**
	 * 丢弃老数据重新刷新
	 * 
	 * @author longtao.li
	 * 
	 */
	class RefreshDataTask extends Task {

		boolean flag = false; // 是否清空原数据
		boolean noshops = false; // 是否显示过滤无店铺界面

		public RefreshDataTask(int id, boolean flag, boolean noshops) {
			super(id);
			this.flag = flag;
			this.noshops = noshops;
		}

		@Override
		public void run() {
			if (!NetWorkCenter.isNetworkConnected(getActivity())) { // 断网
				runOnUi(new Runnable() {
					@Override
					public void run() {
						showViewById(VIEW_WIFIFAILUER);
					}
				});
				return;
			}
			runOnUi(new Runnable() {
				public void run() {
					if (footerView != null) {
						shopList.getRefreshableView().removeFooterView(footerView);
						footerView = null;
					}
				}
			});
			if (pageNext == 0) {
				dismissProgressDialog();
				runOnUi(new Runnable() {
					public void run() {
						shopList.onRefreshComplete();
					}
				});
				return;
			}

			CodeListResult<ShopItem> result = null;
			try {
				shopListReq.setPage(pageNext); // 页号
				result = mShopsModel.v2_3queryShopList(shopListReq);
			} catch (RetrofitError e) {
				switch (e.getKind()) {
				case HTTP:
					showViewById(VIEW_OUTTIME);
					break;
				case CONVERSION:
					showViewById(VIEW_LOADFAILURE);
					break;
				case NETWORK:
					showViewById(VIEW_OUTTIME);
					break;
				case UNEXPECTED:
					showViewById(VIEW_LOADFAILURE);
					break;
				}
			} finally {
				dismissProgressDialog();
				runOnUi(new Runnable() {
					public void run() {
						shopList.onRefreshComplete();
					}
				});
			}

			// 判断是不是用户的最后操作,最后任务的ID如果比此任务的ID大则丢弃请求结果
			if (getID() < lastTask.getID()) {
				return;
			}

			if (result != null && result.code == 1) {
				refreshUI(result, flag, noshops);
			} else {
				showViewById(VIEW_LOADFAILURE);
			}

		}

	}

	@UiThread
	void refreshUI(CodeListResult<ShopItem> result, boolean flag, boolean noshops) {
		List<ShopItem> list = result.getList();

		if (list == null || list.size() == 0) {// 没有数据返回
			shopItems.clear();
			shopAdapter.notifyDataSetChanged();
			if (noshops) {
				showViewById(VIEW_NOSHOPS);
			} else {
				showViewById(VIEW_NOFILTERSHOPS);
			}
		} else {
			showViewById(VIEW_SHOPLIST);
			if (!flag) {// 有数据返回
				pageNext = result.page;
				shopItems.addAll(list);
				shopAdapter.notifyDataSetChanged();
			} else {// 有数据返回但需要回到顶部
				shopItems.clear();
				pageNext = result.page;
				shopItems.addAll(list);
				shopAdapter.notifyDataSetChanged();
				shopList.getRefreshableView().setSelection(0);
			}

		}

	}

	private void refreshData(boolean clean, boolean noshops) {
		lastTask = new RefreshDataTask(lastTask.getID() + 1, clean, noshops);
		executeTask(lastTask);
	}

	private String affertName; // 从哪个界面传递过来的

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	protected void obtainInfo() {
		FmInfoBean infoBean = getInfoBean();
		// 修改activity的bug
		if (infoBean != null) {
			affertName = infoBean.getOriginClzz().getName();

			if (!TextUtils.isEmpty(affertName) && affertName.equals(MyCouPonActivity_.class.getName())) {
				defParams();
				typeTv.setText("全部类型");
				activityTv.setText("特色优惠");
				List<String> shopList = (List<String>) infoBean.getData();
				String[] shopArr = new String[shopList.size()];
				for (int i = 0; i < shopList.size(); i++) {
					shopArr[i] = shopList.get(i);
				}
				shopListReq.setCodeList(shopArr);
				refreshData(true, true);

			} 
//			else if (!TextUtils.isEmpty(affertName) && affertName.equals(AddrSearchActivity_.class.getName())) {
//				searchAddr = (MyAddress) infoBean.getData();
//				showViewById(VIEW_LOADING);
//				isLocationReady = true;
//				defParams();
//				if (searchAddr != null) {
//					shopListReq.setLat(searchAddr.getLat());
//					shopListReq.setLng(searchAddr.getLng());
//					try {
//						double la = Double.parseDouble(searchAddr.getLat());
//						double ln = Double.parseDouble(searchAddr.getLng());
//						latLngReq.setLat(la);
//						latLngReq.setLng(ln);
//					} catch (Exception e) {
//						latLngReq.setLat(lat);
//						latLngReq.setLng(lng);
//					}
//				}
//
//				String addrName = searchAddr.getAddrName();
//				if (addrName != null && !"".equals(addrName)) {
//					locationAddr.setText(addrName);
//				}
//				activityTv.setText("特色优惠");
//				typeTv.setText("全部类型");
//				if (mShopTypePop != null) {
//					mShopTypePop.loadShopType(shopTypeReq, typeIv);
//				}
//				if (mActivityTypePop != null) {
//					mActivityTypePop.loadActType(latLngReq, activityIv);
//				}
//				if (mSortTypePop != null) {
//					mSortTypePop.init();
//				}
//
//				refreshData(true, true);
//
//			} 
			else if (!TextUtils.isEmpty(affertName) && affertName.equals(IndexFragment_.class.getName())) {
				showViewById(VIEW_LOADING);
				isLocationReady = true;
				defParams();
				activityTv.setText("全部优惠");
				typeTv.setText("全部类型");

				if (mShopTypePop != null) {
					mShopTypePop.loadShopType(shopTypeReq, typeIv);
				}
				if (mActivityTypePop != null) {
					mActivityTypePop.setAllShops(true);
					mActivityTypePop.loadActType(latLngReq, activityIv);
				}
				if (mSortTypePop != null) {
					mSortTypePop.init();
				}
			}

		}

	}

	/**
	 * 恢复默认搜索状态
	 */
	private void defParams() {
		pageNext = 1;
		shopListReq.setPage(1);
		shopListReq.setKey("");
		shopListReq.setScope("");
		shopListReq.setSortType("");
		shopListReq.setCodeList(new String[] {});
	}

	/**
	 * 恢复过滤搜索状态
	 */
	private void defFilter() {
		pageNext = 1;
		shopListReq.setPage(1);
		shopListReq.setKey("");
	}

	@Override
	public void retry() {

	}

	@Override
	public void pwdError() {

	}

	@Override
	public void netError() {

	}

	private void executeAnim(final TextView keyText) {
		cancelAnim();
		pointTimer = new Timer();
		pointTimerTask = new TimerTask() {
			@Override
			public void run() {
				runOnUi(new Runnable() {
					public void run() {
						if (point == 0) {
							keyText.setText("正在定位");
							point = 1;
						} else if (point == 1) {
							keyText.setText("正在定位.");
							point = 2;
						} else if (point == 2) {
							keyText.setText("正在定位..");
							point = 3;
						} else {
							keyText.setText("正在定位...");
							point = 0;
						}
					}
				});
			}
		};
		pointTimer.schedule(pointTimerTask, 0, 1000);
	}

	/**
	 * 取消动画
	 */
	private void cancelAnim() {
		if (pointTimer != null) {
			pointTimer.cancel();
			pointTimer = null;
		}
		if (pointTimerTask != null) {
			pointTimerTask.cancel();
			pointTimerTask = null;
		}
	}

	/**
	 * 显示店铺列表：1 显示断网：2 显示加载数据失败：3 显示定位失败：4 显示加载中：5 显示请求超时：6 显示没有数据：7
	 */
	@UiThread
	void showViewById(int i) {
		loadShoping.setVisibility(View.GONE);
		shopList.setVisibility(View.GONE);
		mErrorHintView.setVisibility(View.GONE);

		switch (i) {
		case 1:
			stopRotateAnim();
			shopList.setVisibility(View.VISIBLE);
			mErrorHintView.close();
			break;

		case 2:
			stopRotateAnim();
			mErrorHintView.netError(new OperateListener() {
				@Override
				public void operate() {
					startRotateAnim();
					loadShoping.setVisibility(View.VISIBLE);
					refreshData(true, true);
				}
			});
			break;

		case 3:
			stopRotateAnim();
			mErrorHintView.loadFailure(new OperateListener() {
				@Override
				public void operate() {
					startRotateAnim();
					loadShoping.setVisibility(View.VISIBLE);
					refreshData(true, true);
				}
			});
			break;

		case 4:
			stopRotateAnim();
			mErrorHintView.locationFail(new OperateListener() {
				@Override
				public void operate() {
					startRotateAnim();
					loadShoping.setVisibility(View.VISIBLE);
					executeAnim(locationAddr);
					isLocationReady = false;
					mBaiduLocationService.startLocation();
				}
			});
			break;

		case 5:
			startRotateAnim();
			break;

		case 6:
			stopRotateAnim();
			mErrorHintView.timeOut(new OperateListener() {
				@Override
				public void operate() {
					startRotateAnim();
					loadShoping.setVisibility(View.VISIBLE);
					refreshData(true, true);
				}
			});
			break;

		case 7:
			stopRotateAnim();
			mErrorHintView.noShops("附近没有外卖店铺\n我们正在努力覆盖");
			break;

		case 8:
			stopRotateAnim();
			mErrorHintView.noFilterShops(new FilterShopImp() {
				@Override
				public void resetShop() {
					showViewById(VIEW_LOADING);
					defParams();
					activityTv.setText("特色优惠");
					typeTv.setText("全部类型");
					if (mShopTypePop != null) {
						mShopTypePop.loadShopType(shopTypeReq, typeIv);
					}
					if (mActivityTypePop != null) {
						mActivityTypePop.loadActType(latLngReq, activityIv);
					}
					if (mSortTypePop != null) {
						mSortTypePop.init();
					}

					refreshData(true, true);
				}
			}, "查看全部店铺");
			break;
		}
	}

	RotateAnimation rotateAnimation;

	@UiThread
	void startRotateAnim() {
		loadShoping.setVisibility(View.VISIBLE);
		mErrorHintView.close();
		// 创建一个RotateAnimation对象（以某个点为圆心旋转360度）
		// 相对于自己的360度旋转
		if (rotateAnimation == null) {
			rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
					0.5f);
			rotateAnimation.setDuration(1000);
			rotateAnimation.setRepeatCount(-1); // ndroid:repeatCount
												// 重复的次数，默认为0，必须是int，可以为-1表示不停止
			rotateAnimation.setInterpolator(new LinearInterpolator());
			rotateImg.setAnimation(rotateAnimation);
		}
		rotateAnimation.start();
	}

	@UiThread
	void stopRotateAnim() {
		loadShoping.setVisibility(View.GONE);
		if (rotateAnimation != null) {
			rotateAnimation.cancel();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.shops_filter_type_ll:
			mShopTypePop.showPop();
			mSortTypePop.dismissPop();
			mActivityTypePop.dismissPop();
			break;

		case R.id.shops_filter_conditions_ll:
			mSortTypePop.showPop();
			mShopTypePop.dismissPop();
			mActivityTypePop.dismissPop();
			break;

		case R.id.shops_filter_activities_ll:
			mActivityTypePop.showPop();
			mShopTypePop.dismissPop();
			mSortTypePop.dismissPop();
			break;
		default:
			break;
		}

	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregister();
	}
	
	private void register(){
		IntentFilter filter = new IntentFilter(BroadcastConstant.SEND_CHANGE_ADDRESS);
		mContext.registerReceiver(mRefAddrReceiver, filter);
	}
	
	private void unregister(){
		if(mRefAddrReceiver!=null){
			mContext.unregisterReceiver(mRefAddrReceiver);
		}
	}
	
	BroadcastReceiver mRefAddrReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(BroadcastConstant.SEND_CHANGE_ADDRESS)){
				searchAddr = (MyAddress) intent.getSerializableExtra(BroadcastConstant.ADDR_PARAMS);
				showViewById(VIEW_LOADING);
				isLocationReady = true;
				defParams();
				if (searchAddr != null) {
					shopListReq.setLat(searchAddr.getLat());
					shopListReq.setLng(searchAddr.getLng());
					try {
						double la = Double.parseDouble(searchAddr.getLat());
						double ln = Double.parseDouble(searchAddr.getLng());
						latLngReq.setLat(la);
						latLngReq.setLng(ln);
					} catch (Exception e) {
						latLngReq.setLat(lat);
						latLngReq.setLng(lng);
					}
				}

				String addrName = searchAddr.getAddrName();
				if (addrName != null && !"".equals(addrName)) {
					locationAddr.setText(addrName);
				}
				activityTv.setText("特色优惠");
				typeTv.setText("全部类型");
				if (mShopTypePop != null) {
					mShopTypePop.loadShopType(shopTypeReq, typeIv);
				}
				if (mActivityTypePop != null) {
					mActivityTypePop.loadActType(latLngReq, activityIv);
				}
				if (mSortTypePop != null) {
					mSortTypePop.init();
				}

				refreshData(true, true);
			}
			
		}
	};
	

}
